package com.canyou.oss;

import cn.hutool.core.io.FileUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

/**
 * 七牛oss文件上传
 *
 * @author fy
 * @date 20/05/13 14:48
 */
@Service
@Slf4j
public class QiNiuOssService {

    @Autowired
    private QiNiuOssProperties config;

    /**
     * 流上传文件到七牛oss
     *
     * @param stream
     * @param fileName
     * @return
     */
    public DefaultPutRet upload(InputStream stream, String fileName) {
        // 构造一个带指定Zone对象的配置类Region.region0()
        Configuration cfg = new Configuration();
        // ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // ...生成上传凭证，然后准备上传
        String accessKey = config.getAccessKey();
        String secretKey = config.getSecretKey();
        String bucket = config.getBucket();
        // 默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(stream, key, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            try {
                log.error(r.bodyString());
            } catch (QiniuException ex2) {
                log.error(ex2.getMessage(), ex2);
            }
            throw new RuntimeException("上传文件到七牛OSS失败", ex);
        }
    }

    /**
     * 文件上传到七牛oss
     *
     * @param file
     * @param fileName
     * @return
     */
    public DefaultPutRet upload(File file, String fileName) {
        return upload(FileUtil.getInputStream(file), fileName);
    }

    /**
     * 构建私有控件文件访问url
     *
     * @param fileName
     * @return
     */
    public String privateDownloadUrl(String fileName) {
        String domainOfBucket = config.getHost();
        String encodedFileName = UrlUtils.urlEncode(fileName).replace("+", "%20");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        String accessKey = config.getAccessKey();
        String secretKey = config.getSecretKey();
        Auth auth = Auth.create(accessKey, secretKey);
        // 1小时，可以自定义链接过期时间
        long expireInSeconds = 3600;
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return finalUrl;
    }

}
